package com.captainbank.tcl.tclapplication.utils;


import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by TCL on 2018/12/27.
 */

public class AESUtils {
    private static final String key = "1010101010101010";
    private static final String iv = "6666666666666666";
    /**
     * aes 加密
     * @param data
     * @return
     */
    public static String encryptData(String key, String iv,String data){
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return Base64.encodeToString(encrypted,Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encryptData(String data){
        return encryptData(key, iv, data);
    }


    /**
     * aes 解密
     * @param data 密文
     * @return
     */
    public static String decryptData(String key, String iv,String data){
        try {
            byte[] encrypted1 = Base64.decode(data,Base64.DEFAULT);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String decryptData(String data){
        return decryptData(key, iv,data);
    }


    //eg
    public static void main(String[] args) {
        try {
            String str = "{\"mobile\":\"18121259693\"}";
            System.out.println("原文:"+str);

            String aesStr = AESUtils.encryptData(str);
            System.out.println("密文:"+aesStr);

            // 发给服务端
            String encode = AESUtils.decryptData(aesStr);
            System.out.println("解密:"+encode);
        }catch (Exception e){
            e.printStackTrace();
        }




    }

}